package com.zj.androidcamera.util;

import android.graphics.Rect;

public class ByteUtil {

    /**
     * 将 yuv420sp 格式的图像数据转换为 argb
     *
     * @param yuv    yuv格式图像数据
     * @param width  图像宽
     * @param height 图像高
     * @param rect   指定图像区域
     * @return argb格式像素数组
     */
    public static int[] convertYUV420spToARGB(byte[] yuv, int width, int height, Rect rect) {
        int frameSize = width * height;

        int[] pixels = new int[rect.width() * rect.height()];
        int uvp = 0, u = 0, v = 0;
        for (int j = rect.top, yp = 0; j < rect.bottom; j++) {
            uvp = frameSize + (j >> 1) * width + rect.left;
            if ((rect.left & 1) != 0) {
                uvp -= 1;
                v = (0xff & yuv[uvp++]) - 128;
                u = (0xff & yuv[uvp++]) - 128;
            }
            for (int i = rect.left; i < rect.right; i++, yp++) {
                int y = (0xff & ((int) yuv[j * width + i])) - 16;
                if (y < 0) y = 0;
                if ((i & 1) == 0) {
                    v = (0xff & yuv[uvp++]) - 128;
                    u = (0xff & yuv[uvp++]) - 128;
                }

                int y1192 = 1192 * y;
                int r = (y1192 + 1634 * v);
                int g = (y1192 - 833 * v - 400 * u);
                int b = (y1192 + 2066 * u);

                if (r < 0) r = 0;
                else if (r > 262143) r = 262143;
                if (g < 0) g = 0;
                else if (g > 262143) g = 262143;
                if (b < 0) b = 0;
                else if (b > 262143) b = 262143;

                pixels[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff);
            }
        }

        return pixels;
    }

}
